<?php

namespace App\Models;

use Carbon\Carbon;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Model;

class ProjectHasExtra extends Model
{
    use HasDateTimeFormatter;

    public $timestamps = false;

    protected $table = "project_has_extra";

    protected $casts = [
        'range_data' => 'json',
        'start_date' => 'date',
        'end_date' => 'date',
    ];

    const TIME_TYPE_OPTIONS = [
        0 => '全天生效',
        1 => '指定时段',
    ];

    const DAY_TYPE_OPTIONS = [
        0 => "长期有效(每天)",
        1 => "日期范围内有效"
    ];
    const EXTRA_TYPE_OPTIONS = [
        0 => '休息(停止预约)',
        1 => '更改预约量'
    ];

    public function project(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Project::class, 'project_id', 'id');
    }

    public function getRangeTimeDataAttribute($val)
    {
        if (!$this->range_data) return null;
        if (is_array($this->range_data)) return $this->range_data;
        $this->range_data = json_decode($this->range_data, true);
        return $this->range_data;
    }

    public function checkTimeIsBlock($time, $date = null): bool
    {
        if ($this->day_type === 1 && $date) {
            if (!($this->start_date && $this->end_date))
                return false;

            if (!$date->isBetween($this->start_date, $this->end_date))
                return false;
        }
        if ($this->time_type === 0) return true;

        if (!$this->range_time_data || !count($this->range_time_data)) return false;
        foreach ($this->range_time_data as $timeName) {
            if (hasOverlap($timeName, $time)) {
                return true;
            }
        }
        return false;
    }

    public function checkTimeIsExtra($extras, $time)
    {


    }

}
